package com.mkx.rest.tenant;

import com.mkx.application.dto.UserDTO;
import com.mkx.application.dto.request.CreateUserRequest;
import com.mkx.application.dto.request.CreateTenantUserRequest;
import com.mkx.application.service.UserApplicationService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 租户端用户REST API控制器
 */
@RestController
@RequestMapping("/tenant/users")
@Validated
public class TenantUserController {
    
    @Autowired
    private UserApplicationService userApplicationService;
    
    /**
     * 创建用户（租户端）
     * 租户管理员创建用户并关联到当前租户
     */
    @PostMapping
    public ResponseEntity<UserDTO> createUser(
            @RequestParam String tenantId,
            @Valid @RequestBody CreateUserRequest request) {
        // 租户端创建用户的业务逻辑
        UserDTO userDTO = userApplicationService.createUser(request);
        
        // 自动将创建的用户关联到当前租户
        CreateTenantUserRequest tenantUserRequest = new CreateTenantUserRequest();
        tenantUserRequest.setTenantId(tenantId);
        tenantUserRequest.setUserId(userDTO.getId());
        // 可以设置默认角色，或者从请求中获取
        tenantUserRequest.setRoleId(null); // 这里可以设置默认角色ID
        
        userApplicationService.createTenantUser(tenantUserRequest);
        
        return new ResponseEntity<>(userDTO, HttpStatus.CREATED);
    }
    
    /**
     * 查询用户列表（租户端）
     * 只能查询当前租户下的用户
     */
    @GetMapping
    public ResponseEntity<List<UserDTO>> findUsers(
            @RequestParam String tenantId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        // 租户端查询本租户用户的业务逻辑
        List<UserDTO> users = userApplicationService.findUsersByTenant(tenantId, page, size);
        return ResponseEntity.ok(users);
    }
}